package com.sz.biz.common.customer.service.impl;

import com.sz.biz.common.constants.CommCodes;
import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.customer.entity.CustomerMessageRel;
import com.sz.biz.logistics.base.dto.CustomerMessageRelDto;
import com.sz.biz.common.customer.service.CustomerMessageRelService;
import com.sz.biz.common.customer.service.CustomerMessageRelTypeService;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.system.entity.SysDict;
import com.sz.common.core.system.service.SysDictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: Johnboy <br>
 * Date: 2017-08-10 15:44:00
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CustomerMessageRelServiceImpl extends AbstractService implements CustomerMessageRelService {
    @Autowired
    private SysDictService dictService;

    @Autowired
    private CustomerMessageRelTypeService customerMessageRelTypeService;

    @Override
    protected String getMapperNamespace() {
        return "CustomerMessageRelMapper";
    }

    @Override
    public void save(CustomerMessageRel customerMessageRel) {
        checkDataValid(customerMessageRel);
        dao.save(this.getSqlName("insertSelective"), customerMessageRel);
    }

    @Override
    public void save(List<CustomerMessageRelDto> list,int customerId) {
        List<String> messageTypeCollection = getMessageTypes();
        for (CustomerMessageRelDto customerMessageRelDto : list) {
            if (customerMessageRelDto != null && customerMessageRelDto.getRefParentId() != 0) {
                ParamData pd = new ParamData();
                if (customerId == 0) {
                    throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "customerId");
                }
                if (customerMessageRelDto.getRefParentId() == 0) {
                    throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "refParentId");
                }
                pd.put("customerId", customerId);
                pd.put("refParentId", customerMessageRelDto.getRefParentId());
                this.dao.delete(this.getSqlName("deleteByCustomerIdAndRefParentId"), pd);
                if (customerMessageRelDto.getRefIds() != null && customerMessageRelDto.getRefIds().size() > 0) {
                    List<CustomerMessageRel> customerMessageRels = dtoConvertCustomerMessageRel(customerMessageRelDto, messageTypeCollection);
                    if (customerMessageRels.size() > 0) {
                        for (CustomerMessageRel customerMessageRel : customerMessageRels) {
                            customerMessageRel.setCustomerId(customerId);
                            checkDataValid(customerMessageRel);
                            save(customerMessageRel);
                        }
                    }
                }
            }
        }
    }

    private List<String> getMessageTypes(){
       List<SysDict> messageNoticeTypes = dictService.findByCatalog(CommCodes.SYS_DICT_MESSAGE_NOTICE_TYPE);
       List<String> messageNoticeTypesStrs = new ArrayList<>();
       if(messageNoticeTypes!=null && messageNoticeTypes.size()>0){
           messageNoticeTypes.forEach(sysDict -> messageNoticeTypesStrs.add(sysDict.getCode()));
       }
       return messageNoticeTypesStrs;
    }

    @Override
    public List<CustomerMessageRel> queryByCustomerId(int customerId) {
        List<CustomerMessageRel> customerMessageRels = this.dao.findForList(this.getSqlName("selectByCustomerId"),
                customerId, CustomerMessageRel.class);
        return customerMessageRels;
    }

    @Override
    public CustomerMessageRel queryByCustomerIdAndRefId(int customerId, int refId) {
        ParamData pd = new ParamData();
        pd.put("customerId",customerId);
        pd.put("refId",refId);
        return  (CustomerMessageRel)this.dao.findForObject(this.getSqlName("selectByCustomerIdAndRefId"),pd);
    }

    private void checkDataValid(CustomerMessageRel customerMessageRel) {
        if (customerMessageRel != null) {
            if (customerMessageRel.getCustomerId() == 0) {
                throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "customerId");
            }
            if (customerMessageRel.getRefId() == 0) {
                throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "refId");
            }
            if (customerMessageRel.getRefParentId() == 0) {
                throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "refParentId");
            }
            if (StringUtils.isEmpty(customerMessageRel.getSendType())) {
                throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "sendType");
            }
            if (!customerMessageRelTypeService.checkParentIdContainRefIds(customerMessageRel.getRefParentId(), customerMessageRel.getRefId())) {
                throw Exceptions.bizException(ErrorCodes.ERROR_COMMON,  "参数refId" +customerMessageRel.getRefId() + "数据异常");
            }
        }
    }

    public List<CustomerMessageRel> dtoConvertCustomerMessageRel(CustomerMessageRelDto customerMessageRelDto, List<String> messageTypeCollection) {
        List<CustomerMessageRel> list = new ArrayList<>();
        if (customerMessageRelDto != null && customerMessageRelDto.getRefIds() != null) {
            List<String> messageTypes = customerMessageRelDto.getSendTypes();
            if (messageTypes == null || messageTypes.size() < 0) {
                throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "sendType");
            }
            for (String type : messageTypes) {
                if (messageTypeCollection.contains(type)) {
                    continue;
                }
                else {
                    throw Exceptions.bizException(ErrorCodes.ERROR_COMMON, "没有" + type + "的通知方式");
                }
            }
            String types = String.join(",", messageTypes);
            for (int refId : customerMessageRelDto.getRefIds()) {
                CustomerMessageRel customerMessageRel = new CustomerMessageRel();
                BeanUtils.copyProperties(customerMessageRelDto, customerMessageRel);
                customerMessageRel.setRefId(refId);
                customerMessageRel.setSendType(types);
                list.add(customerMessageRel);
            }
        }
        return list;
    }
}
